# -*- coding: utf-8 -*-
from zope import schema

from zope.interface import implements, alsoProvides

from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm

from plone.autoform.interfaces import IFormFieldProvider

from plone.supermodel import model

from plone.app.dexterity import MessageFactory as _
from Products.bpContents.articulo import IArticulo
from zope.component import adapts

options = SimpleVocabulary([
    SimpleTerm(value=True, title=_(u'Yes')),
    SimpleTerm(value=False, title=_(u'No')),
    ])


class IAllowDiscussion(model.Schema):

    model.fieldset(
        'discussion',
        label=_(u"Discussion"),
        fields=['allow_discussion'],
    )

    allow_discussion = schema.Choice(
        title=_(u'Allow discussion'),
        description=_(u'Allow discussion for this content object.'),
        vocabulary=options,
        required=False,
        default=None,
    )

alsoProvides(IAllowDiscussion, IFormFieldProvider)

class AllowDiscussion(object):
    """Store tags in the Dublin Core metadata Subject field. This makes
    tags easy to search for.
    """
    from plone.app.discussion.interfaces import IDiscussionSettings
    implements(IAllowDiscussion)
    adapts(IArticulo)

    def __init__(self, context):
        self.context = context

    def __call__(self):
        context = aq_inner(self.context)

        # Fetch discussion registry
        registry = queryUtility(IRegistry)
        settings = registry.forInterface(IDiscussionSettings, check=False)

        # Check if discussion is allowed globally
        if not settings.globally_enabled:
            return False

        # Check if discussion is allowed on the content object
        if context.allow_discussion is not None:
            return context.allow_discussion

